package com.yvan.platform;

import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.Maps;
import com.yvan.codeslave.batch.TemplateSetting;
import lombok.SneakyThrows;

import java.util.Map;

public class Settings {

    public Map<String, Object> global;
    private String templateBase;
    private String path;
    private JsonWapper jw;

    public Settings(String path) {
        this.path = path;
        reload();
    }

    @SneakyThrows
    public void reload() {
        JsonNode jn = FileUtils.readYamlToJsonNode(this.path);
        SettingLoader setting = new JsonWapper(jn).asObject(SettingLoader.class, "load");
        templateBase = setting.getBaseDir();
        jw = YvanUtil.readYaml(setting, jn);
        global = jw.asMap("global");
    }

    public Map<String, TemplateSetting> getTemplates() {
        Map<String, TemplateSetting> ret = Maps.newLinkedHashMap();
        for (String key : jw.keys("templates")) {
            TemplateSetting templateSetting = jw.asObject(TemplateSetting.class, "templates", key);
            ret.put(key, templateSetting);
        }
        return ret;
    }

    @Override
    public String toString() {
        return jw.toString(true);
    }

    public String getPath() {
        return path;
    }

    public JsonWapper getJw() {
        return jw;
    }

    public String getTemplateBase() {
        return templateBase;
    }

    public void setTemplateBase(String templateBase) {
        this.templateBase = templateBase;
    }
}
